package com.boot;

import com.boot.entity.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.mvc.ParameterizableViewController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Stream;

public class RoleInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getSession().getAttribute("loginUser");
        if (user == null) {
            return true;
        }

        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            CheckPermission annotation = method.getMethodAnnotation(CheckPermission.class);
            if (annotation != null) {
                int[] value = annotation.value();
                for (int item : value) {
                    if (item == user.getRole()) {
                        return true;
                    }
                }
                response.sendRedirect("/user/permissionDenied");
                System.out.println("用户权限不够");
                return false;
            }

            Class<?> classController = method.getBeanType();
            CheckPermission classAnnotation = classController.getAnnotation(CheckPermission.class);
            if (classAnnotation != null) {
                int[] value = classAnnotation.value();
                for (int item : value) {
                    if (item == user.getRole()) {
                        return true;
                    }
                }
                response.sendRedirect("/user/permissionDenied");
                System.out.println("用户权限不够");
                return false;
            }
        }
        return true;
    }
}
